#ifndef __M_LOG_H__
#define __M_LOG_H__

#include "util.hpp"
#include "level.hpp"
#include "message.hpp"
#include "formatter.hpp"
#include "sink.hpp"
#include "looper.hpp"
#include <vector>
#include <list>
#include <atomic>
#include <unordered_map>
#include <cstdarg>
#include <type_traits>

namespace maglog {

// 日志基类，用于定义日志器的基本功能
class Logger {
    public:
        enum class Type {
            LOGGER_SYNC = 0,  // 同步日志器
            LOGGER_ASYNC      // 异步日志器
        };
        using ptr = std::shared_ptr<Logger>;

        // 构造函数，初始化日志器的名称、格式、输出、日志级别等
        Logger(const std::string &name, 
               Formatter::ptr formatter,
               std::vector<LogSink::ptr> &sinks, 
               LogLevel::value level = LogLevel::value::DEBUG)
            : _name(name), _level(level), _formatter(formatter),
              _sinks(sinks.begin(), sinks.end()) {}

        std::string loggerName() { return _name; } // 获取日志器名称
        LogLevel::value loggerLevel() { return _level; } // 获取日志器级别

        // 各种日志级别的日志输出函数
        void debug(const char *file, size_t line, const char *fmt, ...) {
            if (!shouldLog(LogLevel::value::DEBUG)) return;
            va_list al;
            va_start(al, fmt);
            log(LogLevel::value::DEBUG, file, line, fmt, al);
            va_end(al);
        }

        void info(const char *file, size_t line, const char *fmt, ...) {
            if (!shouldLog(LogLevel::value::INFO)) return;
            va_list al;
            va_start(al, fmt);
            log(LogLevel::value::INFO, file, line, fmt, al);
            va_end(al);
        }

        void warn(const char *file, size_t line, const char *fmt, ...) {
            if (!shouldLog(LogLevel::value::WARN)) return;
            va_list al;
            va_start(al, fmt);
            log(LogLevel::value::WARN, file, line, fmt, al);
            va_end(al);
        }

        void error(const char *file, size_t line, const char *fmt, ...) {
            if (!shouldLog(LogLevel::value::ERROR)) return;
            va_list al;
            va_start(al, fmt);
            log(LogLevel::value::ERROR, file, line, fmt, al);
            va_end(al);
        }

        void fatal(const char *file, size_t line, const char *fmt, ...) {
            if (!shouldLog(LogLevel::value::FATAL)) return;
            va_list al;
            va_start(al, fmt);
            log(LogLevel::value::FATAL, file, line, fmt, al);
            va_end(al);
        }

    public:
        // 日志构建器基类，用于构建日志器
        class Builder {
            public:
                using ptr = std::shared_ptr<Builder>;
                Builder() : _level(LogLevel::value::DEBUG), 
                            _logger_type(Logger::Type::LOGGER_SYNC) {}

                void buildLoggerName(const std::string &name) { _logger_name = name; }
                void buildLoggerLevel(LogLevel::value level) { _level = level; }
                void buildLoggerType(Logger::Type type) { _logger_type = type; }
                void buildFormatter(const std::string pattern) { _formatter = std::make_shared<Formatter>(pattern); }
                void buildFormatter(const Formatter::ptr &formatter) { _formatter = formatter; }
                
                // 模板函数，用于构建不同类型的日志输出
                template<typename SinkType, typename ...Args>
                void buildSink(Args &&...args) { 
                    auto sink = SinkFactory::create<SinkType>(std::forward<Args>(args)...);
                    _sinks.push_back(sink); 
                }

                virtual Logger::ptr build() = 0;

            protected:
                Logger::Type _logger_type;
                std::string _logger_name;
                LogLevel::value _level;
                Formatter::ptr _formatter;
                std::vector<LogSink::ptr> _sinks;
        };

    protected:
        // 检查是否应该记录指定级别的日志
        bool shouldLog(LogLevel::value level) { return level >= _level; }

        // 实现日志的格式化与记录
        void log(LogLevel::value level, const char *file, size_t line, const char *fmt, va_list al) {
            char *buf;
            std::string msg;
            int len = vasprintf(&buf, fmt, al);
            if (len < 0) {
                msg = "格式化日志消息失败！";
            } else {
                msg.assign(buf, len);
                free(buf);
            }
            LogMsg lm(_name, file, line, std::move(msg), level);
            std::stringstream ss;
            _formatter->format(ss, lm);
            logIt(std::move(ss.str()));
        }

        // 纯虚函数，子类需实现日志输出的具体方式
        virtual void logIt(const std::string &msg) = 0;

    protected:
        std::mutex _mutex;
        std::string _name;
        Formatter::ptr _formatter;
        std::atomic<LogLevel::value> _level;
        std::vector<LogSink::ptr> _sinks;
};

// 同步日志器类，继承自Logger，负责同步日志输出
class SyncLogger : public Logger {
    public:
        using ptr = std::shared_ptr<SyncLogger>;

        SyncLogger(const std::string &name, 
                   Formatter::ptr formatter,
                   std::vector<LogSink::ptr> &sinks, 
                   LogLevel::value level = LogLevel::value::DEBUG)
            : Logger(name, formatter, sinks, level) {
            std::cout << LogLevel::toString(level) << " 同步日志器: " << name << " 创建成功...\n";
        }

    private:
        // 同步日志记录实现
        virtual void logIt(const std::string &msg) override {
            std::unique_lock<std::mutex> lock(_mutex);
            if (_sinks.empty()) { return; }
            for (auto &it : _sinks) {
                it->log(msg.c_str(), msg.size());
            }
        }
};

// 异步日志器类，继承自Logger，负责异步日志输出
class AsyncLogger : public Logger {
    public:
        using ptr = std::shared_ptr<AsyncLogger>;

        AsyncLogger(const std::string &name, 
                    Formatter::ptr formatter, 
                    std::vector<LogSink::ptr> &sinks, 
                    LogLevel::value level = LogLevel::value::DEBUG)
            : Logger(name, formatter, sinks, level),
              _looper(std::make_shared<AsyncLooper>(std::bind(&AsyncLogger::backendLogIt, this, std::placeholders::_1))) {
            std::cout << LogLevel::toString(level) << " 异步日志器: " << name << " 创建成功...\n";
        }

    protected:
        // 异步日志记录实现，将消息推送到异步循环器
        virtual void logIt(const std::string &msg) override {
            _looper->push(msg);
        }

        // 后端日志记录实现
        void backendLogIt(Buffer &msg) {
            if (_sinks.empty()) { return; }
            for (auto &it : _sinks) {
                it->log(msg.begin(), msg.readAbleSize());
            }
        }

    protected:
        AsyncLooper::ptr _looper;
};

// 本地日志构建器类，继承自Logger::Builder，用于构建同步或异步日志器
class LocalLoggerBuilder : public Logger::Builder {
    public:
        virtual Logger::ptr build() override {
            if (_logger_name.empty()) {
                std::cout << "日志器名称不能为空！！";
                abort();
            }
            if (_formatter.get() == nullptr) {
                std::cout << "当前日志器：" << _logger_name << " 未检测到日志格式，默认设置为[ %d{%H:%M:%S}%T%t%T[%p]%T[%c]%T%f:%l%T%m%n ]!\n";
                _formatter = std::make_shared<Formatter>();
            }
            if (_sinks.empty()) {
                std::cout << "当前日志器：" << _logger_name << " 未检测到落地方向，默认设置为标准输出!\n";
                _sinks.push_back(std::make_shared<StdoutSink>());
            }
            Logger::ptr lp;
            if (_logger_type == Logger::Type::LOGGER_ASYNC) {
                lp = std::make_shared<AsyncLogger>(_logger_name, _formatter, _sinks, _level);
            } else {
                lp = std::make_shared<SyncLogger>(_logger_name, _formatter, _sinks, _level);
            }
            return lp;
        }
};

// 日志管理器类，负责管理和存储多个日志器实例（单例模式）
class loggerManager {
    private:
        std::mutex _mutex;
        Logger::ptr _root_logger;
        std::unordered_map<std::string, Logger::ptr> _loggers;

        // 私有构造函数，初始化根日志器
        loggerManager() { 
            std::unique_ptr<LocalLoggerBuilder> slb(new LocalLoggerBuilder());
            slb->buildLoggerName("root");
            slb->buildLoggerType(Logger::Type::LOGGER_SYNC);
            _root_logger = slb->build();
            _loggers.insert(std::make_pair("root", _root_logger));
        }

        // 禁止复制构造和赋值
        loggerManager(const loggerManager&) = delete;
        loggerManager &operator=(const loggerManager&) = delete;

    public:
        // 获取日志管理器实例（单例模式）
        static loggerManager& getInstance() {
            static loggerManager lm;
            return lm;
        }

        // 判断日志器是否已存在
        bool hasLogger(const std::string &name) {
            std::unique_lock<std::mutex> lock(_mutex);
            return _loggers.find(name) != _loggers.end();
        }

        // 添加日志器
        void addLogger(const std::string &name, const Logger::ptr logger) {
            std::unique_lock<std::mutex> lock(_mutex);
            _loggers.insert(std::make_pair(name, logger));
        }

        // 获取日志器
        Logger::ptr getLogger(const std::string &name) {
            std::unique_lock<std::mutex> lock(_mutex);
            auto it = _loggers.find(name);
            if (it == _loggers.end()) {
                return Logger::ptr();
            }
            return it->second;
        }

        // 获取根日志器
        Logger::ptr rootLogger() {
            std::unique_lock<std::mutex> lock(_mutex);
            return _root_logger;
        }
};

// 全局日志构建器类，继承自Logger::Builder，用于构建并注册日志器
class GlobalLoggerBuilder : public Logger::Builder {
    public:
        virtual Logger::ptr build() override {
            if (_logger_name.empty()) {
                std::cout << "日志器名称不能为空！！";
                abort();
            }
            assert(!loggerManager::getInstance().hasLogger(_logger_name));
            if (_formatter.get() == nullptr) {
                std::cout << "当前日志器：" << _logger_name << " 未检测到日志格式，默认设置为[ %d{%H:%M:%S}%T%t%T[%p]%T[%c]%T%f:%l%T%m%n ]!\n";
                _formatter = std::make_shared<Formatter>();
            }
            if (_sinks.empty()) {
                std::cout << "当前日志器：" << _logger_name << " 未检测到落地方向，默认设置为标准输出!\n";
                _sinks.push_back(std::make_shared<StdoutSink>());
            }
            Logger::ptr lp;
            if (_logger_type == Logger::Type::LOGGER_ASYNC) {
                lp = std::make_shared<AsyncLogger>(_logger_name, _formatter, _sinks, _level);
            } else {
                lp = std::make_shared<SyncLogger>(_logger_name, _formatter, _sinks, _level);
            }
            loggerManager::getInstance().addLogger(_logger_name, lp);
            return lp;
        }
};

} // namespace maglog

#endif // __M_LOG_H__
